package mini.statement;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Random;

import mini.Proc;
import mini.StatementList;
import mini.compiler.CodeGenerator;
import mini.expr.Expr;

public class WhileStatement extends Statement {

    private Expr expr;
    private StatementList s;

    public WhileStatement(Expr e, StatementList list){
		expr = e;
		s = list;
    }

    public void eval(HashMap<String, Integer> hm, HashMap<String, Proc> functiontable, LinkedList var){
		while (expr.eval(hm, functiontable, var)>0)
		    s.eval(hm, functiontable, var);
    }
    
    public String parse(HashMap<String,Integer> hm, HashMap<String, Proc> functiontable, LinkedList var){
    	
    	
    	/* Code from the slide:
    	 * while_stmt → while expr do S od
                    while expr > 0 then S od 
			L1:  Codee      ; result stored in t
       		LD t         ;
       		JMN L2   ; jump if t  0
       		JMZ L2
       		CodeS
       		JMP L1
			L2:
    	 */
    	String label1 = nextTempLocation();
    	String label2 = nextTempLocation();
    	
    	CodeGenerator cg = new CodeGenerator();
    	
    	// Do what you need to in order to evaluate/load expression
    	String exprValue = expr.parse(hm,functiontable,var);
    	cg.appendCode(  label1 +": " + exprValue );
    	cg.addLoadAccumulator( expr.getTempVariable() );
       
    	//put in the jumps
    	cg.addJMN(label2);
    	cg.addJMZ(label2);
    	
    	//parse and add s
    	cg.appendCode(s.parse(hm,functiontable,var));
    	
    	//add the jump to 1
    	cg.addJMP(label1);
    	
    	//add label 2
    	cg.addLabel( label2 );
    	
    	// And return this code
    	return cg.getCode();

    }
}
